package com.wica.facebook;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;

import java.util.Collections;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import temporary.NSError;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.Button;
import android.widget.TextView;

import com.codecarpet.fbconnect.FBDialog;
import com.codecarpet.fbconnect.FBLoginActivity;
import com.codecarpet.fbconnect.FBLoginButton;
import com.codecarpet.fbconnect.FBRequest;
import com.codecarpet.fbconnect.FBSession;
import com.codecarpet.fbconnect.FBDialog.FBDialogDelegate;
import com.codecarpet.fbconnect.FBLoginButton.FBLoginButtonStyle;
import com.codecarpet.fbconnect.FBRequest.FBRequestDelegate;
import com.codecarpet.fbconnect.FBSession.FBSessionDelegate;
import com.wica.facetube.R;
import com.wica.view.ListOfMoviesTabs;

public class Facebook extends Activity{
    // /////////////////////////////////////////////////////////////////////////////////////////////////
    // This application will not work until you enter your Facebook application's API key here:

    private static final String kApiKey = "9209dc6a3ee783213152ab316074b52e"; // "<YOUR API KEY>";

    // Enter either your API secret or a callback URL (as described in documentation):
    private static final String kApiSecret = "5fafeccf3bcae3e59773468cd82fd250"; // "<YOUR SECRET KEY>";
    private static final String kGetSessionProxy = null; // "<YOUR SESSION CALLBACK)>";

    // /////////////////////////////////////////////////////////////////////////////////////////////////

    private FBSession _session;
    private FBLoginButton _loginButton;
    private TextView _label;
    private Button _permissionButton;
    private Button _feedButton;
    private Handler mHandler;

	private Configuration newConfig=null;

	private boolean firstTimeHere=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!internetNetworkAvailable())
        	showDialog(1);
        else {

        if (firstTimeHere){
        firstTimeHere=false;
    	Log.v("facebook","onCreate"+"__doberdan");

        // I would log off
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);  
        FBSessionDelegateImpl delegate;

    if (newConfig==null){
    	mHandler = new Handler();
    	if (kGetSessionProxy != null) {
			_session = FBSession.getSessionForApplication_getSessionProxy(kApiKey, kGetSessionProxy,delegate = new FBSessionDelegateImpl() );
        } else {
            _session = FBSession.getSessionForApplication_secret(kApiKey, kApiSecret, delegate= new FBSessionDelegateImpl());
        }
//    	showDialog(1);
        setContentView(R.layout.mainfb);

        _label = (TextView) findViewById(R.id.label);
        _permissionButton = (Button) findViewById(R.id.permissionButton);
        _feedButton = (Button) findViewById(R.id.feedButton);

        _loginButton = (FBLoginButton) findViewById(R.id.login);
        _loginButton.setStyle(FBLoginButtonStyle.FBLoginButtonStyleWide);        
                
        if (PreferenceManager.getDefaultSharedPreferences(this).getInt("userID", -1)==-1){
        	_session.logout(this);
        	_session.resume(this);
//        	_loginButton.FBLoginButton((Context)this);
//        	_loginButton = new FBLoginButton(this);
//        	_loginButton.init();
            Intent intent = new Intent(this, FBLoginActivity.class);
            this.startActivity(intent);
        } else {
        	_session.resume(this);
        }            ;
//        _session.resume(this);
//        Intent intent = new Intent(this, FBLoginActivity.class);
//      this.startActivity(intent);
    	}
        }
        }
    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.v("Facebook", "Facebook_BACK");
        	return true;
        }else{
        	return super.onKeyDown(keyCode, event);
        }
    }

    protected boolean internetNetworkAvailable() {
        // Local Variables
    	ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
        int i;
        
        for (i=0;i<allNetworkInfo.length;i++){
        	NetworkInfo networkInfoItem = allNetworkInfo[i];        	
            if (networkInfoItem.isAvailable()){
            	return true;
            }// if
        }// for
		return false;
	}// internetNetworkAvailable method

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//    	char c = (char)event.getUnicodeChar();
//    Toast.makeText(this, "down '" + c + "'", Toast.LENGTH_SHORT).show
//    ();
//    return super.onKeyDown(keyCode, event);
//    }        


    protected Dialog onCreateDialog(int id) {
    	return new AlertDialog.Builder(this)
        		.setIcon(R.drawable.stat_sample)
                .setTitle(R.string.inicial_dialog_title)                
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .create();
    }//onCreateDialog method
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      //ignore orientation change
    	super.onConfigurationChanged(null);
//    	this.newConfig=newConfig;
    	Log.v("facebook","onconfigurationchanged");
//       	Toast.makeText(this, "Due to an error on CodeCarpet library only portrait orientation is allowed. ", Toast.LENGTH_LONG).show();
    } 
    
    
    @Override 
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState); 
    	Log.v("facebook","onSaveInstanceState");
    }

    
    
    // /////////////////////////////////////////////////////////////////////////////////////////////////

    private void askPermission() {
        // FBPermissionDialog* dialog = [[[FBPermissionDialog alloc] init] autorelease];
        // dialog.delegate = self;
        // dialog.permission = @"status_update";
        // [dialog show];
    }

    private void publishFeed() {
        // FBFeedDialog* dialog = [[[FBFeedDialog alloc] init] autorelease];
        // dialog.delegate = self;
        // dialog.templateBundleId = 9999999;
        // dialog.templateData = @"{\"key1\": \"value1\"}";
        // [dialog show];
    }

    // /////////////////////////////////////////////////////////////////////////////////////////////////

    private class FBDialogDelegateImpl extends FBDialogDelegate {

        public void didFailWithError(FBDialog dialog, NSError error) {
            _label.setText(error.toString());
        }

    }

    public class FBSessionDelegateImpl extends FBSessionDelegate {

        public void session_didLogin(FBSession session, Long uid) {
            mHandler.post(new Runnable() {
                public void run() {
                    _permissionButton.setVisibility(View.VISIBLE);
                    _feedButton.setVisibility(View.VISIBLE);
                }
             });

            String fql = "select uid,name from user where uid == " + session.getUid();
            Map<String, String> params = Collections.singletonMap("query", fql);
            FBRequest.requestWithDelegate(new FBRequestDelegateImpl()).call("facebook.fql.query", params);
        }

        public void sessionDidLogout(FBSession session) {
            mHandler.post(new Runnable() {
               public void run() {
                   _label.setText("");
                   _permissionButton.setVisibility(View.INVISIBLE);
                   _feedButton.setVisibility(View.INVISIBLE);
               }
            });
        }

    }

    public class FBRequestDelegateImpl extends FBRequestDelegate {

		private String uid="";

		public void request_didLoad(FBRequest request, Object result) {
            
            String name = null;
            
            if (result instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) result;
                try {
                    JSONObject jo = jsonArray.getJSONObject(0);
                    name = jo.getString("name");
                    uid = jo.getString("uid");
                    Intent intent = new Intent(Facebook.this, ListOfMoviesTabs.class);
                    intent.putExtra("userID", Long.valueOf(uid));
                    Log.v("facebook", "USERID "+Long.valueOf(uid));
                	setResult(RESULT_OK,intent);
                	finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            _label.setText("Logged in as " + name +"with uid "+uid);
        }

        public void request_didFailWithError(FBRequest request, NSError error) {
            _label.setText("Error: " + error);
        }        

    }
}

